﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.Micro.Validation;
using System.ComponentModel.Composition;
using Zcu.PanelComposer.Interfaces;
using Zcu.PanelComposer.Models.Model;
using System.ComponentModel.DataAnnotations;
using Caliburn.Micro;
using Zcu.PanelComposer.ViewModels.Events;

namespace Zcu.PanelComposer.ViewModels.Pages
{
    /// <summary>
    /// Zakladaci/editacni stranka pro solution.
    /// </summary>
    [Export(typeof(IModule))]
    public class NewSolutionViewModel : ValidatingScreen<NewSolutionViewModel>
    {
        #region Fields

        /// <summary>
        /// Reference na logger.
        /// </summary>
        private readonly ILog _log = LogManager.GetLog(typeof(NewSolutionViewModel));

        #endregion

        #region Properties

        /// <summary>
        /// Gets a value indicating whether this instance is edit.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is edit; otherwise, <c>false</c>.
        /// </value>
        public bool IsEditMode { get; private set; }

        private Solution _SelectedSolution;
        /// <summary>
        /// Gets or sets the selected solution.
        /// </summary>
        /// <value>
        /// The selected solution.
        /// </value>
        public Solution SelectedSolution
        {
            get { return _SelectedSolution; }
            set
            {
                if (_SelectedSolution != value) _SelectedSolution = value;
                NotifyOfPropertyChange(() => SelectedSolution);
            }
        }

        /// <summary>
        /// Pristup na databazi.
        /// </summary>
        [Import]
        public IRepository Repository { get; private set; }

        /// <summary>
        /// Nazev solutionu.
        /// </summary>
        private string _SolutionName;
        /// <summary>
        /// Nazev solutionu.
        /// </summary>
        [Required]
        public string SolutionName
        {
            get { return _SolutionName; }
            set
            {
                if (_SolutionName != value) _SolutionName = value;
                NotifyOfPropertyChange(() => SolutionName);
                NotifyOfPropertyChange(() => CanSaveAction);
            }
        }

        #endregion

        #region Guard properties

        /// <summary>
        /// Guard vlastnost nad tlacitkem Save.
        /// </summary>
        public bool CanSaveAction { get { return !HasErrors; } }

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="NewSolutionViewModel"/> class.
        /// </summary>
        public NewSolutionViewModel()
        {
            /// todo do resources
            DisplayName = "New solution";
            ModuleName = PageNames.NewSolution;
            MenuVisible = false;
            Order = 99;
        }

        #endregion

        #region Overrided methods

                /// <summary>
        /// Udalost, ktera je volana hned po vytvoreni screenu.
        /// </summary>
        public override void OnReconstruct()
        {
            base.OnReconstruct();

            // registrace zachycovani udalosti zmeny projektu.
            EventAggregator.Subscribe(this);
        }

        /// <summary>
        /// Pri aktivaci okna zkontrolujeme zda jde o editaci ci zalozeni noveho.
        /// Nasledne nacteme data z projektu do ViewModelu.
        /// </summary>
        protected override void OnActivate()
        {
            base.OnActivate();

            // zjisteni jestli jde o editaci ci novy projekt
            if (IsEditMode = Context != null && Context is Solution)
            {
                _SelectedSolution = (Solution)Context;
            }
            else
            {
                _SelectedSolution = new Solution();
            }

            // nacteni dat z instance projektu
            LoadData();
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Akce, vyvolana stiskem tlacitka "Save solution".
        /// Ulozeni dat.
        /// </summary>
        public void SaveAction()
        {
            try
            {
                SelectedSolution.DisplayName = SolutionName;

                if (IsEditMode)
                {
                    SelectedSolution.UpdatedDate = DateTime.Now;
                }
                else
                {
                    SelectedSolution.CreatedDate = DateTime.Now;
                    Repository.Add<Solution>(SelectedSolution);
                }

                // commit do DB
                Repository.Commit();
                // zmena aktivniho solutionu
                EventAggregator.Publish(new ActiveSolutionEvent(SelectedSolution));
                // presmerovani na detail solutionu
                Navigate(PageNames.SolutionProjects);
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                Repository.RollBackAll();
            }
        }

        /// <summary>
        /// Akce, vyvolana stiskem tlacitka "Back action".
        /// </summary>
        public void BackAction()
        {
            Navigate(this.SourcePage);
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Loads the data.
        /// </summary>
        private void LoadData()
        {
            SolutionName = SelectedSolution.DisplayName;
        }

        #endregion
    }
}
